<template>
    <div ref="compareChart" class="chart-container"></div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  import http from '../../http/index.js'
  
  export default {
    name: 'ClassroomCompare',
    props: {
      classroomId: {
        type: String,
        required: true
      }
    },
    data() {
      return {
        courseValueList: [
          /*{ name: 'Python数据分析方向', classAvg: 80, allAvg: 85 },
          { name: '自然语言处理方向', classAvg: 78, allAvg: 75 },
          { name: '图像处理方向', classAvg: 67, allAvg: 65 },
          { name: '数据采集方向', classAvg: 90, allAvg: 82 },
          { name: '大数据开发方向', classAvg: 71, allAvg: 75 },
          { name: 'R语言数据分析方向', classAvg: 55, allAvg: 68 }*/
        ],
        courseTitleList: []
      };
    },
    methods: {
      initCompareChart() {
        const chartDom = this.$refs.compareChart;
        const myChart = echarts.init(chartDom);
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {            
              type: 'shadow'        
            }
          },
          legend: {
            data: ['班级均分', '所有均分']
          },
          xAxis: {
            type: 'category',
            data: this.courseTitleList,
            axisLabel: {
              show: false
            }
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '班级均分',
              type: 'bar',
              data: this.courseValueList.map(course => course.classAvg),
              emphasis: {
                focus: 'series'
              },
              markLine: {
                data: [{ type: 'average', name: '平均值' }]
              }
            },
            {
              name: '所有均分',
              type: 'bar',
              data: this.courseValueList.map(course => course.allAvg),
              emphasis: {
                focus: 'series'
              },
              markLine: {
                data: [{ type: 'average', name: '平均值' }]
              }
            }
          ]
        };
        myChart.setOption(option);
      },
      fetchCourseData() {
        //从后端通过班级ID获取课程均分
        http({
         method: 'get',
         url: '/api/classroom/grade',
         params: {
          classroomId: this.classroomId
         }
       }).then(res => {
         if (res) {
           this.courseValueList = Object.values(res);
           this.courseTitleList = Object.keys(res);
           console.log(this.courseValueList);
           console.log(this.courseTitleList);
           this.initCompareChart();
         }
       }).catch(error => {
          console.error(error);
       });
      }
    },
    mounted() {
      this.fetchCourseData(); 
    }
  };
  </script>
  
  <style scoped>
  .chart-container {
    width: 100%;
    height: 500px;
  }
  </style>
  